﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Flurl.Http;
using Newtonsoft.Json.Linq;
using Pay.Core;
using Pay.DTO;
using Pay.DTO.rpay;
using Pay.IService;
using Pay.TO;

namespace Pay.Service {
	public class RpayService : ServiceBase2, IPayService, IDisposable {
		private IUnitOfWork _iUnitOfWork;
		private ISettingService _iSettingService;
		private IMerchantService _iMerchantService;
		private IChargeService _iChargeService;
		private IProfitDayService _iProfitDayService;
		private IBillService _iBillService;
		private IPayHtmlService _iPayHtmlService;
		private IRegionService _iRegionService;
		private RpaySign _rpaySign;

		public RpayService(IUnitOfWork iUnitOfWork, ISettingService iSettingService,
								IMerchantService iMerchantService, IChargeService iChargeService,
								IProfitDayService iProfitDayService, IBillService iBillService,
								IPayHtmlService iPayHtmlService, IRegionService iRegionService) : base(iUnitOfWork) {
			_iUnitOfWork = iUnitOfWork;
			_iSettingService = iSettingService;
			_iMerchantService = iMerchantService;
			_iChargeService = iChargeService;
			_iProfitDayService = iProfitDayService;
			_iBillService = iBillService;
			_iPayHtmlService = iPayHtmlService;
			_iRegionService = iRegionService;
			_rpaySign = new RpaySign();
		}

		#region 扫码的
		/// <summary>
		/// 生成二维码扫码请求通道封装
		/// </summary>
		/// <returns>The pay gateway.</returns>
		/// <param name="model">Model.</param>
		/// <typeparam name="T">The 1st type parameter.</typeparam>
		public Task<native_result> NativePay(native_model model) {
			throw new NotImplementedException();
		}
		#endregion

		#region 支付异步通知
		/// <summary>
		/// 回调支付通知，商户返回OK，不再回调了，流程是先调用ChargeService的NotifyOrder，
		/// 返回值判断是调用哪个通道，再调用本方法，最后调用ChargeService的Update
		/// </summary>
		/// <returns>The notify.</returns>
		/// <param name="order_no">Order.</param>
		public async Task<string> Notify(string merchant_no, string order_no) {
			string result = string.Empty;
			charge_dto order = _iChargeService.Get(merchant_no, order_no);
			try {
				var data = new pay_notity {
					tran_amount = ((int)(order.order_amount * 100)).ToString(), order_no = order.order_no, transaction_no = order.pay_info.transaction_no,
					pay_time = order.pay_info.pay_time.HasValue ? order.pay_info.pay_time.Value : order.order_time,
					status = (order.status == ChargeStatus.Finish ? 1 : 2)
				};
				//失败的要再查询通道判断是否真失败,处理掉单
				//if (order.status != ChargeStatus.Finish) {
				//	var pay_model = new hx_head_base();
				//	pay_model.client_trans_id = order.order_no;
				//	pay_model.trans_timestamp = DateTime.Now.ToUnix();
				//	pay_model.data = data.ToJson();
				//	pay_model.sign = _rpaySign.Sign(pay_model);
				//	var resultApi = await _rpaySign.PayGateway<hx_query_result>(pay_model);
				//	if (resultApi != null) {
				//		if (resultApi.resp_code == "000000" && resultApi.data.resp_code == "PAY_SUCCESS" /*&& resultApi.data.withdrawals_status == "WITHDRAWALS_SUCCESS"*/) {
				//			data.status = 1;
				//			var pay_time = DateTime.Now;
				//			_iChargeService.FailOrUnConfirmToSuceess(merchant_no, order.order_no, pay_time);
				//		}
				//	}
				//}
				data.result_msg = (data.status == 1 ? "支付成功" : order.fail);
				if (string.IsNullOrEmpty(order.notify)) return "OK";
				var notify_result = await order.notify.PostJsonAsync(ApiResultToJson.Json(data)).ReceiveJson<ResultMessage<string>>();
				result = notify_result.data;
				var log = IocHelper.Get<ILogHelper>("info");
				log.Info(order.order_no + ":" + notify_result.ToJson());
			} catch (Exception ex) {
				var log = IocHelper.Get<ILogHelper>("info");
				log.Error("订单通道查询异常:" + order.order_no);
				string message = string.Format("消息类型：{0}\r\n消息内容：{1}\r\n引发异常的方法：{2}\r\n引发异常源：{3}"
								, ex.GetType().Name, ex.Message, ex.TargetSite, ex.Source + ex.StackTrace);
				log.Error(message);
			}
			return result;
		}

		/// <summary>
		/// 代付通知－不可用
		/// </summary>
		/// <returns>The transfer.</returns>
		/// <param name="order_no">Order.</param>
		public Task<string> NotifyTransfer(string merchant_no, string order_no) {
			throw new NotImplementedException();
		}
		#endregion

		#region 实名、T0额度-不可用
		/// <summary>
		/// 查询代付T0额度
		/// </summary>
		/// <returns>The quota.</returns>
		/// <param name="merchant_no"></param>
		/// <param name="busiType">0：对公 1：对私</param>
		public Task<quota_result> Quota(string merchant_no, string busiType) {
			throw new NotImplementedException();
		}
		#endregion

		#region 快捷同卡同出
		/// <summary>
		/// 快捷支付
		/// </summary>
		/// <returns>The receive.</returns>
		/// <param name="model">Model.</param>
		public async Task<quick_pay_result> QuickPay(quick_pay_model model) {
			var binder = _iMerchantService.Get(model.bind_no);
			var setting = _iSettingService.Get();
			string merCode = "";
            var binder_registers = _iMerchantService.GetRegisters(binder.id);
            var register = binder_registers.FirstOrDefault(c => c.pay_channel == PayChannel.RPAY);
			if (register == null) {
				var res = await MerchantRegister(binder.id, "A");
				if (res.result_code != 1000)
					return ApiResultToJson.Json<quick_pay_result>(res.result_msg, 2001);
				else
					merCode = res.merchant_no;
			} else
				merCode = register.merchant_no;
			//return ApiResultToJson.Json<quick_pay_result>("商户未进件，不能支付", 2001);
			string pay_code = model.pay_code;
			model.settle_type = "T0";
            var binder_payments = _iMerchantService.GetPayments(binder.id);
            var payment = binder_payments.FirstOrDefault(c => c.payment.channel == model.pay_channel);
			var settle = payment.settles.First(c => c.settle_type == model.settle_type && c.code == pay_code);
			//查询费率是否与进件一致
			var fee_query = new fee_query_req { mch_id = merCode, nonce_str = model.nonce };
			var resultQtyApi = await _rpaySign.PayGateway<fee_query_resp>(fee_query, "/api/queryfee");
			if (resultQtyApi != null && resultQtyApi.status == "0000" && resultQtyApi.result_code == "0000") {
				if (decimal.Parse(resultQtyApi.fee0) / 1000M != model.fee && int.Parse(resultQtyApi.d0fee) != model.settle_fee) {
					var model1 = new merchant_edit_m03();
					model1.mch_id = merCode;
					model1.nonce_str = DtoHelper.RandCode(10);
					model1.payee_bank_id = SetMerchantBankCode(binder.setting.auth_info.bank_code);
					model1.merchant_oper_flag = "M03";
					SetPayType(model1, binder);
					var resultApi2 = await _rpaySign.PayGateway<merchant_resp>(model1, "/api/upReportInfo");
					if (resultApi2 != null && resultApi2.status == "0000" && resultApi2.result_code == "0000") { } else
						return ApiResultToJson.Json<quick_pay_result>("请求费率结算2有误");
				}
			} else
				return ApiResultToJson.Json<quick_pay_result>("请求费率结算有误");
			//同进件数据比较是否一致
			if (model.settle_fee / 100M != settle.settle)
				return ApiResultToJson.Json<quick_pay_result>("结算费与商户进件的结算费不同", 2001);
			if (model.fee != settle.fee)
				return ApiResultToJson.Json<quick_pay_result>("费率与商户进件的费率不同", 2001);
			if (model.pay_fee_amount != (int)Math.Ceiling(decimal.Parse(model.tran_amount) * model.fee))
				return ApiResultToJson.Json<quick_pay_result>("实扣费率金额不正确");
			//把商户请求转为通道请求消息
			var id = Guid.NewGuid().ToString("N");
			var notify = setting.site.api_url + "/rpay_back_notify/" + id;
			var front_notify_url = model.front_notify;
			var dt = DateTime.Now.ToString("yyyyMMddHHmmss");
			var pay_model = new rpay_kj_req {
				mch_id = merCode,
				customerInfo = SecureHelper.Des3EncodeECB(RpaySign.des3_key, string.Format("{0}|{1}|{2}|{3}|{4}", model.account_no, model.account_name, "01", model.id_card, model.mobile)),
				nonce_str = model.nonce, out_order_no = model.order_no, return_url = front_notify_url, notify_url = notify,
				total_fee = model.tran_amount
			};
			var resultApi = await _rpaySign.PayGateway<rpay_kj_resp>(pay_model, "/api/order");
			//调用通道执行并处理返回，请通道响应消息封装为平台响应商户消息
			if (resultApi != null) {
				if (resultApi.status == "0000") {
					if (resultApi.result_code == "0000") {
						var charge = _iChargeService.AddByQuickPay(model);
						//将HTML保存到mongodb
						var ok = _iPayHtmlService.Save(new pay_html_dto { id = id, html = resultApi.html, merchant_no = model.merchant_no, order_no = model.order_no, charge = charge.ToJson() });
						if (ok) {
							var requestUrl = setting.site.api_url + "/pay/html_front/" + id;
							return ApiResultToJson.Json("鉴权成功，待确认支付", new quick_pay_result {
								order_no = model.order_no, protocol_no = "", request_url = requestUrl,
								pay_time = DateTime.Now, transaction_no = "", status = 3
							});
						} else
							return ApiResultToJson.Json<quick_pay_result>("支付页面加载失败");
					} else
						return ApiResultToJson.Json<quick_pay_result>(resultApi.result_msg);
				} else
					return ApiResultToJson.Json<quick_pay_result>(resultApi.message);
			}
			return ApiResultToJson.Json<quick_pay_result>("异常支付");
		}
		/// <summary>
		/// 快捷支付查询
		/// </summary>
		/// <returns>The pay query.</returns>
		/// <param name="model">Model.</param>
		public async Task<pay_notity> QuickPayQuery(refund_model_query model) {
			charge_dto order = _iChargeService.Get(model.merchant_no, model.order_no);
			var data = new pay_notity { status = 2, order_no = model.order_no };
			if (order == null) {
				var obj = _iPayHtmlService.Get(model.merchant_no, model.order_no);
				if (obj != null) {
					var query_model = new rpay_kjquery_req { order_no = model.order_no, nonce_str = model.nonce };
					var resultApi = await _rpaySign.PayGateway<rpay_kjquery_resp>(query_model, "/api/query1");
					if (resultApi != null) {
						if (resultApi.status == "0000") {
							if (resultApi.result_code == "0000" && resultApi.state == "5") {
								var charge = obj.charge.ToObject<charge_dto>();
								data.status = 1; data.pay_time = obj.create_time; data.result_msg = "支付成功"; data.tran_amount = ((int)(charge.amount * 100)).ToString();
								var result = _iChargeService.PaySuceess(obj, data.order_no, data.pay_time);
								if (result > 0) {
									var notifyResult = await Notify(charge.merchant_no, model.order_no);
									_iPayHtmlService.Remove(obj.id);
								}
							} else
								return ApiResultToJson.Json<pay_notity>(resultApi.result_msg);
						} else
							return ApiResultToJson.Json<pay_notity>(resultApi.message);
					}
				} else {
					data.result_code = 1001; data.result_msg = "支付失败";
				}
			} else {
				data.status = order.status == ChargeStatus.Finish ? 1 : 2; data.pay_time = order.order_time; data.transaction_no = order.order_no;
				data.result_msg = order.status == ChargeStatus.Finish ? "支付成功" : "支付失败"; data.tran_amount = ((int)order.amount * 100).ToString();
				if (order.status != ChargeStatus.Finish) data.result_code = 1001;
			}
			return data;
		}
		#endregion

		#region 快捷支付－不可用
		/// <summary>
		/// 快捷支付鉴权成功后发短信
		/// </summary>
		/// <returns>The pay resms.</returns>
		/// <param name="model">model.</param>
		public Task<ApiResultMessage> QuickPaySendsms(quick_sendsms_model model) {
			throw new NotImplementedException();
		}

		/// <summary>
		/// 确认短信验证码
		/// </summary>
		/// <returns>The pay.</returns>
		/// <param name="model">model.</param>
		public Task<quick_pay_result> QuickPay(quick_sms_model model) {
			throw new NotImplementedException();
		}

		/// <summary>
		/// 快捷支付退款
		/// </summary>
		/// <returns>The pay refund.</returns>
		/// <param name="model">Model.</param>
		public Task<refund_result> QuickPayRefund(refund_model model) {
			throw new NotImplementedException();
		}

		/// <summary>
		/// 快捷支付退款查询,并将退款中的单处理为完成
		/// </summary>
		/// <returns>The pay refund.</returns>
		/// <param name="model">Model.</param>
		public Task<refund_result> QuickPayRefundQuery(refund_model_query model) {
			throw new NotImplementedException();
		}
		#endregion

		#region 网关支付-不可用
		/// <summary>
		/// 网关支付银行
		/// </summary>
		/// <returns>The pay bank.</returns>
		public List<type_setting> GatewayPayBank() {
			var banks = new List<type_setting>();
			banks.Add(new type_setting { value = "BOC", text = "中国银行" });
			banks.Add(new type_setting { value = "ABC", text = "中国农业银行" });
			banks.Add(new type_setting { value = "ICBC", text = "中国工商银行" });
			banks.Add(new type_setting { value = "CCB", text = "中国建设银行" });
			banks.Add(new type_setting { value = "COMM", text = "交通银行" });
			banks.Add(new type_setting { value = "PSBC", text = "中国邮政储蓄银行" });
			banks.Add(new type_setting { value = "CMB", text = "招商银行" });
			banks.Add(new type_setting { value = "CMBC", text = "中国民生银行" });
			banks.Add(new type_setting { value = "CITIC", text = "中信银行" });
			banks.Add(new type_setting { value = "CEB", text = "中国光大银行" });
			banks.Add(new type_setting { value = "HXB", text = "华夏银行" });
			banks.Add(new type_setting { value = "GDB", text = "广发银行" });
			banks.Add(new type_setting { value = "CIB", text = "兴业银行" });
			banks.Add(new type_setting { value = "SPDB", text = "上海浦东发展银行" });
			banks.Add(new type_setting { value = "SPAB", text = "平安银行" });
			banks.Add(new type_setting { value = "SHB", text = "上海银行" });
			banks.Add(new type_setting { value = "BJB", text = "北京银行" });
			banks.Add(new type_setting { value = "HZCB", text = "杭州银行" });
			return banks;
		}

		/// <summary>
		/// 发起网关支付
		/// </summary>
		/// <returns>The receive.</returns>
		/// <param name="model">Model.</param>
		public Task<gateway_pay_result> GatewayPay(gateway_pay_model model) {
			throw new NotImplementedException();
		}

		/// <summary>
		/// 网关支付查询
		/// </summary>
		/// <returns>The pay query.</returns>
		/// <param name="model">Model.</param>
		public Task<pay_notity> GatewayPayQuery(refund_model_query model) {
			throw new NotImplementedException();
		}

		/// <summary>
		/// 网关支付退款
		/// </summary>
		/// <returns>The pay refund.</returns>
		/// <param name="model">Model.</param>
		public Task<refund_result> GatewayPayRefund(refund_model model) {
			throw new NotImplementedException();
		}

		/// <summary>
		/// 网关支付退款查询,并将退款中的单处理为完成
		/// </summary>
		/// <returns>The pay refund.</returns>
		/// <param name="model">Model.</param>
		public Task<refund_result> GatewayRefundQuery(refund_model_query model) {
			throw new NotImplementedException();
		}
		#endregion

		#region 代付,T+0转账-不可用
		/// <summary>
		/// 单笔代付
		/// </summary>
		/// <returns>The transfer.</returns>
		/// <param name="model">Model.</param>
		public Task<transfer_result> Transfer(apply_transfer model) {
			throw new NotImplementedException();
		}
		public Task<transfer_result> ReTransfer(long id) {
			throw new NotImplementedException();
		}

		/// <summary>
		/// 代付批处理:生成代付文件，将批号写入提现表，生成代付文件记录，并上传FTP，FTP成功调用代付通知，FTP失败提示手动上传，并去文件记录管理手动代付通知。
		/// </summary>
		/// <returns>The transfer.</returns>
		/// <param name="model">Model.</param>
		public Task<batch_transfer_result> Transfer(batch_transfer model) {
			throw new NotImplementedException();
		}

		/// <summary>
		/// 提交代付批处理报盘通知（平台后台用）
		/// </summary>
		/// <returns>The transfer.</returns>
		/// <param name="batchId">Batch Id.</param>
		public Task<int> TransferNotify(long batchId, string batchFileName, long merchant_id) {
			throw new NotImplementedException();
		}

		/// <summary>
		/// 提交代付批处理查询，返回回盘文件地址后，进行提现记录更新（平台后台用）
		/// </summary>
		/// <returns>The transfer.</returns>
		/// <param name="batchId">Batch Id.</param>
		/// <param name="noticeTranId">报盘通知交易流水号</param>
		public Task<int> TransferBack(long batchId, string noticeTranId, long merchant_id) {
			throw new NotImplementedException();
		}

		/// <summary>
		/// 单笔代付查询
		/// </summary>
		/// <returns>The query.</returns>
		/// <param name="model">Model.</param>
		public Task<transfer_result> TransferQuery(transfer_query model) {
			throw new NotImplementedException();
		}
		#endregion

		#region 代收,T+1转账-不可用
		/// <summary>
		/// 代收签约
		/// </summary>
		/// <returns>The receive.</returns>
		/// <param name="model">Model.</param>
		public Task<ApiResultMessage> InsteadReceive(verify_model model) {
			throw new NotImplementedException();
		}

		/// <summary>
		/// 代收签约
		/// </summary>
		/// <returns>The receive.</returns>
		/// <param name="model">Model.</param>
		public Task<ApiResultMessage> InsteadReceive(verify_model_sms model) {
			throw new NotImplementedException();
		}

		/// <summary>
		/// 单笔代收
		/// </summary>
		/// <returns>The transfer.</returns>
		/// <param name="model">Model.</param>
		public Task<transfer_result> AgencyFund(apply_receive model) {
			throw new NotImplementedException();
		}
		#endregion

		#region 商户进件
		/// <summary>
		/// 返回的是第三方的商户号，opt：A增加，M修改
		/// </summary>
		/// <returns>The register.</returns>
		/// <param name="dto">Dto.</param>
		/// <param name="opt">A增加，M修改.</param>
		public async Task<merchant_register_result> MerchantRegister(merchant_register_model dto, string opt) {
			if (opt == "A") {
				var model = new merchant_req();
				model.nonce_str = DtoHelper.RandCode(10);
				model.payee_bank_id = SetMerchantBankCode(dto.bank_code);
				SetMerchantInfo(model, dto);
				SetPayType(model, dto);
				var resultApi = await _rpaySign.PayGateway<merchant_resp>(model, "/api/report");
				if (resultApi != null) {
					if (resultApi.status == "0000") {
						if (resultApi.result_code == "0000") {
							dto.reg_merchant_no = resultApi.mch_id;
							return ApiResultToJson.Json(new merchant_register_result { merchant_no = dto.reg_merchant_no });
						} else {
							return ApiResultToJson.Json<merchant_register_result>(resultApi.result_msg);
						}
					} else {
						return ApiResultToJson.Json<merchant_register_result>(resultApi.message);
					}
				}
				return ApiResultToJson.Json<merchant_register_result>("信息登记异常");
			} else {
				var model = new merchant_edit_m02();
				model.mch_id = dto.reg_merchant_no;
				model.nonce_str = DtoHelper.RandCode(10);
				model.payee_bank_id = SetMerchantBankCode(dto.bank_code);
				model.merchant_oper_flag = "M02";
				SetMerchantInfo(model, dto);
				var resultApi = await _rpaySign.PayGateway<merchant_resp>(model, "/api/upReportInfo");
				if (resultApi != null && resultApi.status == "0000" && resultApi.result_code == "0000") {
					//return ApiResultToJson.Json(new merchant_register_result { merchant_no = resultApi.mch_id });
				}

				var model1 = new merchant_edit_m03();
				model1.mch_id = dto.reg_merchant_no;
				model1.nonce_str = DtoHelper.RandCode(10);
				model1.payee_bank_id = SetMerchantBankCode(dto.bank_code);
				model1.merchant_oper_flag = "M03";
				SetPayType(model1, dto);
				var resultApi2 = await _rpaySign.PayGateway<merchant_resp>(model1, "/api/upReportInfo");
				if (resultApi2 != null && resultApi2.status == "0000" && resultApi2.result_code == "0000") {
					return ApiResultToJson.Json(new merchant_register_result { merchant_no = resultApi2.mch_id });
				}
			}
			return ApiResultToJson.Json<merchant_register_result>("信息登记异常");
		}

		/// <summary>
		/// 新增商户进件
		/// </summary>
		/// <returns>The register.</returns>
		/// <param name="bind_id">Bind identifier.</param>
		public async Task<merchant_register_result> MerchantRegister(long bind_id, string settle_type,PayChannel channel = PayChannel.None) {
			var binder = _iMerchantService.Get(bind_id);
			var oemer = _iMerchantService.Get(binder.oem_id.Value);
			var model = new merchant_req();
			model.nonce_str = DtoHelper.RandCode(10);
			model.payee_bank_id = SetMerchantBankCode(binder.setting.auth_info.bank_code);
			SetMerchantInfo(model, binder);
			SetPayType(model, binder);
			var resultApi = await _rpaySign.PayGateway<merchant_resp>(model, "/api/report");
			if (resultApi != null) {
				if (resultApi.status == "0000") {
					if (resultApi.result_code == "0000") {
						var dto = binder.setting.auth_info.ToDtoObject<merchant_register_model>();
						dto.pay_channel = PayChannel.RPAY;
						dto.reg_merchant_no = resultApi.mch_id;
						dto.bind_no = binder.merchant_no;
						dto.merchant_no = oemer.merchant_no;
						_iMerchantService.MerchantChannelRegister(dto);
						return ApiResultToJson.Json(new merchant_register_result { merchant_no = dto.reg_merchant_no });
					} else if (resultApi.result_code == "1007") {
						var rpayout_merchant_no = resultApi.result_msg.Replace("不能重复进件", "");
						var dto = binder.setting.auth_info.ToDtoObject<merchant_register_model>();
						dto.pay_channel = PayChannel.RPAY;
						dto.reg_merchant_no = rpayout_merchant_no;
						dto.bind_no = binder.merchant_no;
						dto.merchant_no = oemer.merchant_no;
						_iMerchantService.MerchantChannelRegister(dto);
						return ApiResultToJson.Json(new merchant_register_result { merchant_no = rpayout_merchant_no });
					} else {
						return ApiResultToJson.Json<merchant_register_result>(resultApi.result_msg);
					}
				} else {
					return ApiResultToJson.Json<merchant_register_result>(resultApi.message);
				}
			}
			return ApiResultToJson.Json<merchant_register_result>("信息登记异常");
		}

		/// <summary>
		/// 编辑商户进件
		/// </summary>
		/// <returns>The modify.</returns>
		/// <param name="bind_id">Bind identifier.</param>
		public async Task<merchant_register_result> MerchantModify(long bind_id, string settle_type,PayChannel channel = PayChannel.None) {
			var binder = _iMerchantService.Get(bind_id);
            var binder_registers = _iMerchantService.GetRegisters(binder.id);
            var register = binder_registers.FirstOrDefault(c => c.pay_channel == PayChannel.RPAY);
			var oemer = _iMerchantService.Get(binder.oem_id.Value);
			var model = new merchant_edit_m02();
			model.mch_id = register.merchant_no;
			model.nonce_str = DtoHelper.RandCode(10);
			model.payee_bank_id = SetMerchantBankCode(binder.setting.auth_info.bank_code);
			model.merchant_oper_flag = "M02";
			SetMerchantInfo(model, binder);
			var resultApi = await _rpaySign.PayGateway<merchant_resp>(model, "/api/upReportInfo");
			if (resultApi != null && resultApi.status == "0000" && resultApi.result_code == "0000") { }

			var model1 = new merchant_edit_m03();
			model1.mch_id = register.merchant_no;
			model1.nonce_str = DtoHelper.RandCode(10);
			model1.payee_bank_id = SetMerchantBankCode(binder.setting.auth_info.bank_code);
			model1.merchant_oper_flag = "M03";
			SetPayType(model1, binder);
			var resultApi2 = await _rpaySign.PayGateway<merchant_resp>(model1, "/api/upReportInfo");
			if (resultApi2 != null && resultApi2.status == "0000" && resultApi2.result_code == "0000") { }
			if (resultApi2 != null && !string.IsNullOrEmpty(resultApi2.mch_id)) {
				var dto = binder.setting.auth_info.ToDtoObject<merchant_register_model>();
				dto.pay_channel = PayChannel.RPAY;
				dto.reg_merchant_no = resultApi.mch_id;
				dto.bind_no = binder.merchant_no;
				dto.merchant_no = oemer.merchant_no;
				_iMerchantService.MerchantChannelRegister(dto);
				return ApiResultToJson.Json(new merchant_register_result { merchant_no = resultApi2.mch_id });
			}
			return ApiResultToJson.Json<merchant_register_result>("信息登记异常");
		}

		/// <summary>
		/// 新增商户信息
		/// </summary>
		/// <param name="model"></param>
		/// <param name="user"></param>
		private void SetMerchantInfo(merchant_req model, merchant_dto user) {
			var authinfo = user.setting.auth_info;
			string info = string.Format("{0}|{1}|{2}|{3}|{4}", authinfo.account_no, authinfo.account_name, "01", authinfo.id_card, authinfo.mobile);
			model.customerInfo = SecureHelper.Des3EncodeECB(RpaySign.des3_key, info);
			model.merch_addr = authinfo.province + authinfo.city;
			model.name = authinfo.account_name;
			model.shortName = authinfo.account_name + "小店";
			model.tel = authinfo.mobile;
			model.payee_branch_code = string.IsNullOrEmpty(authinfo.branch_code) ? model.payee_bank_id : authinfo.branch_code;
			var region_ids = _iRegionService.GetRegionIds(authinfo.region_id);
			model.payee_bank_province = region_ids[0].ToString();
			model.payee_bank_city = region_ids[1].ToString();
		}

		private void SetMerchantInfo(merchant_edit_m02 model, merchant_dto user) {
			var authinfo = user.setting.auth_info;
			string info = string.Format("{0}|{1}|{2}|{3}|{4}", authinfo.account_no, authinfo.account_name, "01", authinfo.id_card, authinfo.mobile);
			model.customerInfo = SecureHelper.Des3EncodeECB(RpaySign.des3_key, info);
			model.payee_branch_code = string.IsNullOrEmpty(authinfo.branch_code) ? model.payee_bank_id : authinfo.branch_code;
			var region_ids = _iRegionService.GetRegionIds(authinfo.region_id);
			model.payee_bank_province = region_ids[0].ToString();
			model.payee_bank_city = region_ids[1].ToString();
		}

		private void SetMerchantInfo(merchant_req model, merchant_register_model authinfo) {
			//收款卡号|姓名|证件类型|证件号|手机号 证件类型为:01 证件号:身份证号码 收款卡号为储蓄卡
			model.customerInfo = SecureHelper.Des3EncodeECB(RpaySign.des3_key, string.Format("{0}|{1}|{2}|{3}|{4}",
									authinfo.account_no, authinfo.account_name, "01", authinfo.id_card, authinfo.mobile));
			var region_name = _iRegionService.GetRegionNames(authinfo.region_id);
			model.merch_addr = region_name;
			model.name = authinfo.account_name;
			model.shortName = authinfo.account_name + "小店";
			model.tel = authinfo.mobile;
			model.payee_branch_code = string.IsNullOrEmpty(authinfo.branch_code) ? model.payee_bank_id : authinfo.branch_code;
			var region_ids = _iRegionService.GetRegionIds(authinfo.region_id);
			model.payee_bank_province = region_ids[0].ToString();
			model.payee_bank_city = region_ids[1].ToString();
		}

		private void SetMerchantInfo(merchant_edit_m02 model, merchant_register_model authinfo) {
			//收款卡号|姓名|证件类型|证件号|手机号 证件类型为:01 证件号:身份证号码 收款卡号为储蓄卡
			model.customerInfo = SecureHelper.Des3EncodeECB(RpaySign.des3_key, string.Format("{0}|{1}|{2}|{3}|{4}",
									authinfo.account_no, authinfo.account_name, "01", authinfo.id_card, authinfo.mobile));
			model.payee_branch_code = string.IsNullOrEmpty(authinfo.branch_code) ? model.payee_bank_id : authinfo.branch_code;
			var region_ids = _iRegionService.GetRegionIds(authinfo.region_id);
			model.payee_bank_province = region_ids[0].ToString();
			model.payee_bank_city = region_ids[1].ToString();
		}

		private string SetMerchantBankCode(string bank_code) {
			var banks = new Dictionary<string, string>();
			banks.Add("ABC", "103100000026");
			banks.Add("BCM", "301290000007");
			banks.Add("BOC", "104100000004");
			banks.Add("CCB", "105100000017");
			banks.Add("CEB", "303100000006");
			banks.Add("CGB", "306331003281");
			banks.Add("CIB", "309391000011");
			banks.Add("CITIC", "302100011000");
			banks.Add("CMB", "308584000013");
			banks.Add("CMBC", "305100000013");
			banks.Add("HXB", "304100040000");
			banks.Add("ICBC", "102100099996");
			banks.Add("PSBC", "403100000004");
			banks.Add("SPDB", "310290000013");
			banks.Add("PAB", "307584007998");
			return banks[bank_code];
		}

		private void SetPayType(merchant_req model, merchant_dto binder) {
            var binder_payments = _iMerchantService.GetPayments(binder.id);
            var payment = binder_payments.FirstOrDefault(c => c.payment.channel == PayChannel.RPAY);
			var settle = payment.settles.First(c => c.settle_type == "T0" && c.code == "UNIONPAY");
			model.fee0 = (settle.fee * 1000).ToString("0.0");
			model.d0fee = ((int)(settle.settle * 100)).ToString();
		}

		private void SetPayType(merchant_edit_m03 model, merchant_dto binder) {
            var binder_payments = _iMerchantService.GetPayments(binder.id);
            var payment = binder_payments.FirstOrDefault(c => c.payment.channel == PayChannel.RPAY);
			var settle = payment.settles.First(c => c.settle_type == "T0" && c.code == "UNIONPAY");
			model.fee0 = (settle.fee * 1000).ToString("0.0");
			model.d0fee = ((int)(settle.settle * 100)).ToString();
		}

		private void SetPayType(merchant_req model, merchant_register_model user) {
			model.fee0 = (user.fee * 1000).ToString("0.0");
			model.d0fee = user.settle;
		}

		private void SetPayType(merchant_edit_m03 model, merchant_register_model user) {
			model.fee0 = (user.fee * 1000).ToString("0.0");
			model.d0fee = user.settle;
		}
		#endregion

		#region 对账
		public Task<int> ItpToFile(DateTime create_date) {
			throw new NotImplementedException();
		}
		public int DealItp(long id) {
			throw new NotImplementedException();
		}
		#endregion

		#region 四要素
		/// <summary>
		/// 四要素
		/// </summary>
		/// <returns>The verify.</returns>
		/// <param name="dto">Model.</param>
		public Task<certify_verify_result> CertifyVerify(certify_verify dto) {
			throw new NotImplementedException();
		}

		public Task<mall_result> MallPay(mall_model obj) {
			throw new NotImplementedException();
		}

        public Task<transfer_result> TokenTransfer(long id) {
            throw new NotImplementedException();
        }

        public Task<transfer_result> TokenTransferQuery(transfer_query model) {
            throw new NotImplementedException();
        }
        #endregion
    }
}